<?php
namespace app\controllers\api\fans;

use fate\http\Request;

use app\models\Fans;
use app\models\User;
use app\libs\LibUser;

// 获取粉丝或者关注列表
class ListController extends \fate\web\PureController {

    public function run() {
        $req = Request::getInstance();
        $p = $req->getQueryString('page');
        $type = $req->getQueryString('type');
        $strUid = $req->getQueryString('uid');
        $uid = LibUser::decodeId($strUid);

        $pageSize = 10;

        if(!is_numeric($uid)) {
            $this->ajaxReturn(null, 300002);
            exit;
        }
        if(!is_numeric($p)) {
            $p = 1;
        }

        $where = 'fans' === $type
            ? ('uid=' . $uid)
            : ('fans_uid=' . $uid);
        $fields = 'fans' === $type
            ? 'id,fans_uid as uid'
            : 'id, uid';

        $posts = new Fans();
        $total = $posts->count($where);
        $ret = $posts->getListByPage(
            $fields,
            $where, $p, $pageSize);

        $ret = $this->getUserInfo($ret);

        $this->ajaxReturn([
            'page_size' => $pageSize,
            'current' => $p,
            'total' => $total,
            'data' => $ret
        ]);
    }

    public function getUserInfo($data) {
        if(!$data) {
            return $data;
        }

        $ret = [];
        $user = new User();

        foreach($data as $val) {
            $ret[] = [
                'uid' => $val['uid'],
                'str_uid' => LibUser::encodeId($val['uid']),
                'user_info' => $user->getOne('user_name, avatar', $val['uid'])
            ];
        }

        return $ret;
    }

}
